<template>
     <div class="my-upload">
            <h3>+</h3>                           
                                                       <!-- v-if =sshow -->
            <input type="file" @change="changimg" v-if="showinput">
            <img :src="imgUrl" alt="" v-if="imgUrl" />
          </div>
</template>
<script>
/*
evenet 通过父组件通过$event获取file
  send回调函数 传值：file
  methoods  父组件通过$ref调用此方法
  setimg(url) 设置图片的地址
  setshowinput(bool)控制图片文件框是否出现
*/ 
import path from "path"
// 清除input 文件 v-if =isshow
export default {
    data() {
        return {
            imgUrl:"",
            showinput:false
        }
    },
    mounted() {
        
    },
    computed:{

    },
    methods: {
        // 清空图片
        setImgUrl(url){
            this.imgUrl=url
        },
        // 控制input图片框的出现
        setshowinput(bool){
           this.showinput=bool
        },
         changimg(e) {
      console.log(e);
      let file = e.target.files[0];
      // 文件大小
        if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件大小不能超过2M");
        return;
    }
      let  imgArr =[".jpg",".png",".jpeg",".gif"];
      // 提取文件后缀名
        // let extname=file.name.slice(file.name.lastIndexOf("."))//js -2
      let extname= path.extname(file.name)
      if(!imgArr.includes(extname)){
        errorAlert("请上传正确的格式");
        return
      }
      // console.log(file);
      // 赋值img给user.img
      // 根据图片生成地址
       this.imgUrl =URL.createObjectURL(file)
      //  判断文件类型
      
    //   this.user.img = file;
    //   给父组件wenjian
    this.$emit("sendimg",file)
    },

    },
}
</script>
<style lang="less" scoped>
@import "../less/index.less";
.my-upload {
  width: 150px;
  height: 150px;
  border: 1px dashed @primary;
  position: relative;

  h3 {
    width: 100%;
    height: 100%;
    text-align: center;
    line-height: 150px;
    font-size: @h1;
    font-weight: 400;
    color: @primary;
  }
  input {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
    z-index: 100;
    cursor: pointer;
  }
  img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
  }
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>